package com.luhui.codereview.service.impl

import com.luhui.codereview.service.ProjectService
import com.intellij.openapi.project.Project
import com.luhui.codereview.api.ApiManager
import com.luhui.codereview.api.CodeReviewApi
import com.luhui.codereview.token.ProjectInfo
import com.luhui.codereview.utils.RespBody
import com.luhui.codereview.utils.SerializableUtils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Response
import java.io.File
import java.util.concurrent.CountDownLatch

/**
 * @author luhui
 * @version 1.0
 * @date 2019/11/11 21:02
 */
class ProjectServiceImpl(val project: Project) : ProjectService {

    override fun getCurrentProjectInfo(): ProjectInfo? {
        return this.projectInfo
    }

    private val codeReviewApi: CodeReviewApi = ApiManager.getApiInstance()

    var projectInfo:ProjectInfo? = null

    override fun saveAndGetProjectInfo(): ProjectInfo {
        val projectPath = project.basePath!!
        val saveProjectInfoPath = File(projectPath,"code_review_project.dat")
        var projectInfo = ProjectInfo()
        if(saveProjectInfoPath.exists()){
            //文件已存在 ，则反序列化这个文件，从这个文件中获取信息
            val retObj = SerializableUtils.deSerilializeObject(saveProjectInfoPath.absolutePath)
            if(retObj is HashMap<*, *>){
                projectInfo.id = retObj["id"] as Long
                projectInfo.projectName = retObj["projectName"] as String
            }else{
                projectInfo = retObj as ProjectInfo
            }
        }else {
            val file = File(projectPath)
            val dirPath = file.name
            projectInfo.projectName = dirPath
            GlobalScope.launch {
                val proj = codeReviewApi.saveProjectInfo(projectInfo)
                if (proj != null && proj.success) {
                    val projectId = proj.body
                    projectInfo.id = projectId
                    updateCurrentProjectInfo(projectInfo)
                }
            }
        }
        this.projectInfo = projectInfo
        return projectInfo
    }

    override fun updateCurrentProjectInfo(projectInfo: ProjectInfo) {
        val projectPath = project.basePath!!
        val saveProjectInfoPath = File(projectPath,"code_review_project.dat")
        //序列化至文件系统
        SerializableUtils.serilalizeObject(projectInfo, saveProjectInfoPath.absolutePath)
    }


}
